/* 
 * Copyright (C) 2008-2010 Josef Hardi <josef.hardi@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.bth.student.android.photohand.activity;

import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import edu.bth.student.android.photohand.R;
import edu.bth.student.android.photohand.parser.PicasaWebAlbumHandler;
import edu.bth.student.android.photohand.parser.PicasaWebPhotoHandler;

public class AlbumAdd {

  private static final String TAG = "ALBUM ADD";

  private static final String URL_BASE = 
      "http://picasaweb.google.com/data/feed/api/user/";
  private static final String ALBUM = "/album/";

  static void show(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    LayoutInflater inflater = LayoutInflater.from(activity);

    final View layout = inflater.inflate(R.layout.album_add,
        (ViewGroup) activity.findViewById(R.id.layout_root));
    builder.setView(layout).setPositiveButton(R.string.add_albums,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            EditText textAlbumOwnerId = (EditText) layout
                .findViewById(R.id.album_ownerId);
            String albumOwnerId = textAlbumOwnerId.getText().toString();
            EditText textAlbumName = (EditText) layout
                .findViewById(R.id.album_name);
            String albumName = textAlbumName.getText().toString();

            ProgressDialog progressDialog = ProgressDialog.show(activity, "",
                "Loading. Please wait...", true);
            try {
              ContentResolver content = activity.getContentResolver();
              addAlbumAndPhoto(albumName, albumOwnerId, content);
            } catch (Exception e) {
              String errmsg = e.getMessage();
              String errmsgFull = e.toString();
              String errstr = ((errmsgFull != null) ? errmsgFull : errmsg);

              AlertDialog.Builder error = new AlertDialog.Builder(activity);
              error.setMessage(
                  "An error was encountered while accessing the feed: "
                      + errstr).setCancelable(false).setPositiveButton("OK",
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                      dialog.cancel();
                    }
                  });
              error.create().show();
            }
            progressDialog.dismiss();
          }
        }).setNegativeButton(R.string.cancel,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
          }
        });
    builder.create().show();
  }

  private static void addAlbumAndPhoto(String name, String owner,
      ContentResolver content) throws Exception {
    String albumUrlString = new StringBuilder().append(URL_BASE).append(owner)
        .toString();

    // Get a SAXParser from the SAXPArserFactory.
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    // Get the XMLReader of the SAXParser we created.
    XMLReader reader = parser.getXMLReader();

    // Create a new ContentHandler and apply it to the XML-Reader.
    PicasaWebAlbumHandler albumHandler = new PicasaWebAlbumHandler(content);
    reader.setContentHandler(albumHandler);

    // Parse the XML- data from the URL.
    URL albumUrl = new URL(albumUrlString);
    reader.parse(new InputSource(albumUrl.openStream()));

    String albumName = "";
    String photoUrlString = "";
    Hashtable<String, Uri> albumUris = albumHandler.getAlbumList();
    Set<String> set = albumUris.keySet();
    Iterator<String> iter = set.iterator();

    Log.w(TAG, "Album count: " + set.size());

    while (iter.hasNext()) {
      albumName = iter.next();
      photoUrlString = new StringBuilder().append(albumUrlString).append(ALBUM)
          .append(albumName).toString();

      Log.w(TAG, photoUrlString);
      Log.w(TAG, albumName + " : " + albumUris.get(albumName));

      URL photoUrl = new URL(photoUrlString);

      // Get a new XMLReader.
      reader = parser.getXMLReader();
      PicasaWebPhotoHandler photoHandler = new PicasaWebPhotoHandler(content,
          albumUris.get(albumName));
      reader.setContentHandler(photoHandler);

      reader.parse(new InputSource(photoUrl.openStream()));
    }

  }
}
